package com.shire.shire_interface.filter;

import com.shire.shire_interface.common.utils.StrUtils;
import com.shire.shire_interface.conf.InstanceManager;
import com.shire.shire_interface.model.account.DeviceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DeviceFilter implements Filter {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String ip = getIp(request);
        // 判断访问来源
        String uri = request.getRequestURI().substring(1);
        String k = request.getHeader("k");
        if(StrUtils.isBlank(k)){
            k = request.getParameter("k");
        }
        if(k!=null && k.indexOf(",")>0){
            String[] ks = k.split(",");
            k = ks[0];
        }

        logger.debug("["+ip+"]Req: url="+request.getRequestURL()+", query="+request.getQueryString()+", k="+k);
        request.setAttribute("k", k);

        try{
            DeviceInfo deviceInfo = InstanceManager.getInstance().getDeviceInfoService().getAndSaveDeviceInfo(k, request.getParameter("devicetype"), request.getParameter("ver"), request.getParameter("sysver"), ip);
        }
        catch(Exception e){
            logger.error("查询设备信息异常[k="+k+"]：", e);
            response.getWriter().print("[{}]");
            response.getWriter().flush();
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private String getIp(HttpServletRequest request){
        String ip = request.getHeader("X-Real-IP");
        return ip==null ? request.getRemoteAddr():ip;
    }
}
